package com.example.homework.viewmodels

import UserResponse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework.repositories.RetrofitService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {
    private val _dataFlow: MutableStateFlow<UserResponse?> = MutableStateFlow<UserResponse?>(null)
    val dataFlow: Flow<UserResponse?> = _dataFlow.asStateFlow()
    private val _uiState: MutableStateFlow<UiState> = MutableStateFlow<UiState>(UiState())
    val uiState: Flow<UiState> = _uiState.asStateFlow()

    init {
        updateData()
    }

    fun updateData() {
        viewModelScope.launch {
            _uiState.update {
                _uiState.value.copy(isButtonEnabled = false, isProgressVisible = true)
            }
            try {
                _dataFlow.value = RetrofitService.getDataApi.getData()
            } catch (e: Exception) {
                _dataFlow.value = null
            }
            _uiState.update {
                _uiState.value.copy(isButtonEnabled = true, isProgressVisible = false)
            }
        }
    }
}